/**
 * 
 */
package jvs.peer.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import jvs.peer.io.Channel;
import jvs.peer.io.ChannelManager;


/**
 * @author qiangli
 *
 */
public class PeerURLConnection extends HttpURLConnection {
	private static final ChannelManager man = ChannelManager.getInstance();
	protected String jid = null;
	protected Channel channel = null; 

	/**
	 * @param url <scheme>://<authority><path>?<query>#<fragment>
	 */
	
	public PeerURLConnection(URL url) throws IOException {
		super(url);
		
		jid = url.getAuthority();
		connected = false;
	}

	@Override
	public void connect() throws IOException {
		if (connected) {
			return;
		}
		channel = man.openChannel(jid);
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return channel.getInputStream();
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return channel.getOutputStream();
	}

	@Override
	public void disconnect() {
		try {
			channel.shutdownInput();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			channel.shutdownOutput();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean usingProxy() {
		return false;
	}
}
